<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRoute } from 'vue-router'
import { 
  ElMessage, 
  ElLoading, 
  ElDialog, 
  ElMessageBox,
  ElRate,
  ElTable,
  ElTableColumn,
  ElButton,
  ElIcon,
  ElTooltip,
  ElTag,
  ElTabs,
  ElTabPane,
  ElCard,
  ElEmpty,
  ElPagination,
  ElProgress
} from 'element-plus'
import { ArrowUp, ArrowDown, Loading, Delete, View } from '@element-plus/icons-vue'
import { useAuthStore } from '@/stores/auth'
import { teacherApi } from '@/api/teacher'
import { courseApi } from '@/api/course'

const route = useRoute()
const authStore = useAuthStore()

// 分页和排序相关
const currentPage = ref(1)
const pageSize = ref(10)
const activeTab = ref('students')
const sortOrder = ref('none')

// 课程详情相关
const courseDetailVisible = ref(false)
const currentCourse = ref(null)
const isTeachingCourse = ref(false)
const activeCourseTab = ref('detail')

// 学生进度相关
const studentProgressVisible = ref(false)
const currentStudent = ref(null)
const studentProgressData = ref([])
const loadingProgress = ref(false)
const courseNameMap = ref({})

const loading = ref(true)
const classDetail = ref({
  classInfo: {
    id: Number(route.params.id) || 0,
    className: '数据加载中...',
    classStuNum: 0,
    createTime: null
  },
  students: [],
  courses: []
})

// 学生操作相关方法
const moveStudent = (index, direction) => {
  const students = classDetail.value.students
  if (direction === 'up' && index > 0) {
    [students[index], students[index - 1]] = [students[index - 1], students[index]]
  } else if (direction === 'down' && index < students.length - 1) {
    [students[index], students[index + 1]] = [students[index + 1], students[index]]
  }
}

// 删除学生
const removeStudent = async (studentId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除该学生吗？此操作不可撤销！',
      '警告',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const classId = classDetail.value.classInfo.id
    const response = await teacherApi.removeStudentFromClass(classId, studentId)
    
    if (response.status === 200) {
      ElMessage.success('学生删除成功')
      await loadClassDetail()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除学生失败:', error)
      ElMessage.error('删除学生失败')
    }
  }
}

const getCourseNames = async (courseIds) => {
  try {
    const uniqueIds = [...new Set(courseIds)]
    const promises = uniqueIds.map(id => courseApi.getCourseDetail(id))
    const results = await Promise.all(promises)
    
    results.forEach((res, index) => {
      if (res.data) {
        courseNameMap.value[uniqueIds[index]] = res.data.name || `课程${uniqueIds[index]}`
      }
    })
  } catch (error) {
    console.error('获取课程名称失败:', error)
  }
}

const viewStudentProgress = async (student) => {
  loadingProgress.value = true
  studentProgressVisible.value = true
  currentStudent.value = student
  
  try {
    const teacherId = authStore.userId
    const classId = classDetail.value.classInfo.id
    const response = await teacherApi.getStudentProgress(teacherId, classId, student.id)
    
    const progressData = response.data || []
    const courseIds = progressData.map(item => item.couId).filter(Boolean)
    
    if (courseIds.length > 0) {
      await getCourseNames(courseIds)
    }
    
    studentProgressData.value = progressData.map(item => ({
      id: item.id,
      stuId: item.stuId,
      couId: item.couId,
      courseName: courseNameMap.value[item.couId] || `课程${item.couId}`,
      progress: item.mediaProgress || 0,
      lastStudyTime: item.positioning,
      learnedDuration: item.learnedDuration || 0,
      learnedStatus: item.learnedStatus || '无学习状态信息'
    }))
    
    ElMessage.success('学生进度加载成功')
  } catch (error) {
    console.error('加载学生进度出错:', error)
    ElMessage.error(`加载进度失败: ${error.message}`)
    studentProgressData.value = []
  } finally {
    loadingProgress.value = false
  }
}

// 格式化工具方法
const formatDate = (dateString) => {
  if (!dateString) return '未设置'
  try {
    const date = new Date(dateString)
    return isNaN(date.getTime()) ? '日期格式错误' : 
      date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }).replace(/\//g, '-')
  } catch {
    return '日期格式错误'
  }
}

const formatDuration = (seconds) => {
  if (!seconds) return '0秒'
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  
  let result = ''
  if (hours > 0) result += `${hours}小时`
  if (minutes > 0) result += `${minutes}分钟`
  if (secs > 0 || result === '') result += `${secs}秒`
  
  return result
}

// 计算属性
const sortedStudents = computed(() => {
  if (sortOrder.value === 'none') return classDetail.value.students
  
  return [...classDetail.value.students].sort((a, b) => {
    const nameA = a.stuName?.charAt(0) || ''
    const nameB = b.stuName?.charAt(0) || ''
    return sortOrder.value === 'asc' 
      ? nameA.localeCompare(nameB) 
      : nameB.localeCompare(nameA)
  })
})

const paginatedStudents = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return sortedStudents.value.slice(start, end)
})

// 其他方法
const toggleSortOrder = () => {
  const orders = ['none', 'asc', 'desc']
  const currentIndex = orders.indexOf(sortOrder.value)
  sortOrder.value = orders[(currentIndex + 1) % orders.length]
}

const playVideo = (videoUrl) => {
  if (!videoUrl) {
    ElMessage.warning('视频链接无效')
    return
  }
  window.open(videoUrl, '_blank')
}

const showCourseDetail = async (course) => {
  const loadingInstance = ElLoading.service({
    target: '.class-detail-container',
    text: '加载课程详情中...'
  })
  
  try {
    const [permissionRes, detailRes] = await Promise.all([
      teacherApi.checkTeachingPermission(authStore.userId, course.id),
      courseApi.getCourseDetail(course.id)
    ])
    
    const detailData = detailRes.data || {}
    const uniqueChapters = (detailData.chapters || []).reduce((acc, chapter) => {
      const exists = acc.some(c => c.index === chapter.index && c.title === chapter.title)
      if (!exists) acc.push(chapter)
      return acc
    }, [])
    
    currentCourse.value = {
      id: course.id,
      couName: detailData.name || course.couName,
      couIntroduction: detailData.introduction || course.couIntroduction,
      createTime: course.createTime,
      cou_price: detailData.price || 0,
      cou_coll_num: detailData.collectionCount || 0,
      cou_like_num: detailData.likeCount || 0,
      cou_share_num: detailData.shareCount || 0,
      chapters: uniqueChapters,
      comments: detailData.appraises || []
    }
    
    isTeachingCourse.value = permissionRes.data === true
    courseDetailVisible.value = true
    
  } catch (error) {
    console.error('加载流程出错:', error)
    ElMessage.error(`加载失败: ${error.message}`)
    
    currentCourse.value = {
      ...course,
      chapters: [],
      comments: []
    }
    isTeachingCourse.value = course.tea_id === authStore.userId
    courseDetailVisible.value = true
    
  } finally {
    loadingInstance.close()
  }
}

const editCourse = () => {
  if (isTeachingCourse.value) {
    ElMessage.warning('编辑功能暂未实现')
  } else {
    ElMessage.warning('您没有权限编辑此课程')
  }
}

const loadClassDetail = async () => {
  const loadingInstance = ElLoading.service({
    target: '.class-detail-container',
    lock: true,
    text: '班级数据加载中...',
    background: 'rgba(0, 0, 0, 0.7)'
  })
  
  try {
    const teacherId = authStore.userId
    const classId = Number(route.params.id)
    const response = await teacherApi.getClassDetail(teacherId, classId)
    const responseData = response.data || response

    classDetail.value = {
      classInfo: {
        id: responseData.classInfo?.id || classId,
        className: responseData.classInfo?.className || '未命名班级',
        classStuNum: responseData.classInfo?.classStuNum || responseData.students?.length || 0,
        createTime: responseData.classInfo?.createTime
      },
      students: responseData.students || [],
      courses: responseData.courses || []
    }

    ElMessage.success('班级数据加载成功')
    
  } catch (error) {
    console.error('数据加载异常:', error)
    ElMessage.error(`加载失败: ${error.message}`)
    
    classDetail.value = {
      classInfo: {
        id: Number(route.params.id),
        className: '数据加载异常',
        classStuNum: 0,
        createTime: null
      },
      students: [],
      courses: []
    }
  } finally {
    loading.value = false
    loadingInstance.close()
  }
}

onMounted(() => {
  loadClassDetail()
})
</script>

<template>
  <div class="class-detail-container">
    <el-card class="box-card" shadow="never">
      <!-- 班级基本信息 -->
      <div class="class-info">
        <h2 class="class-title">
          {{ classDetail.classInfo.className }}
          <el-tag 
            v-if="classDetail.classInfo.className.includes('数据')" 
            :type="classDetail.classInfo.className.includes('异常') ? 'danger' : 'warning'"
            size="small">
            {{ classDetail.classInfo.className.includes('异常') ? '异常状态' : '加载状态' }}
          </el-tag>
        </h2>
        <div class="info-grid">
          <div class="info-item">
            <span class="label">班级ID:</span>
            <span class="value">{{ classDetail.classInfo.id }}</span>
          </div>
          <div class="info-item">
            <span class="label">学生人数:</span>
            <span class="value">{{ classDetail.classInfo.classStuNum }}人</span>
          </div>
          <div class="info-item">
            <span class="label">创建时间:</span>
            <span class="value">{{ formatDate(classDetail.classInfo.createTime) }}</span>
          </div>
        </div>
      </div>

      <!-- 标签页导航 -->
      <el-tabs v-model="activeTab" class="detail-tabs">
        <el-tab-pane label="学生管理" name="students">
          <!-- 学生列表（带分页） -->
          <div class="table-header">
            <h3 class="table-title">学生列表 ({{ classDetail.students.length }}人)</h3>
            <el-button 
              type="primary" 
              size="small" 
              @click="toggleSortOrder"
              class="sort-btn"
              plain>
              {{ 
                sortOrder === 'none' ? '默认排序' : 
                sortOrder === 'asc' ? 'A-Z ↑' : 'Z-A ↓' 
              }}
            </el-button>
          </div>
          
          <el-table 
            :data="paginatedStudents" 
            border 
            v-if="classDetail.students.length > 0"
            key="student-table"
            style="width: 100%">
            <el-table-column prop="id" label="学号" width="120" />
            <el-table-column prop="stuName" label="姓名" />
            
            <!-- 合并后的操作列 -->
            <el-table-column label="操作" width="400" align="center">
              <template #default="{row, $index}">
                <div class="student-actions">
                  <!-- 查看进度按钮 -->
                  <el-button
                    type="primary"
                    size="small"
                    @click.stop="viewStudentProgress(row)"
                    class="action-btn">
                    <el-icon><View /></el-icon>
                    <span>查看进度</span>
                  </el-button>
                  
                  <!-- 删除按钮 -->
                  <el-button
                    type="danger"
                    size="small"
                    @click.stop="removeStudent(row.id)"
                    class="action-btn">
                    <el-icon><Delete /></el-icon>
                    <span>删除</span>
                  </el-button>
                  
                  <!-- 上移按钮 -->
                  <el-button
                    size="small"
                    :disabled="$index === 0"
                    @click.stop="moveStudent($index, 'up')"
                    class="move-btn">
                    <el-icon><ArrowUp /></el-icon>
                    <span>上移</span>
                  </el-button>
                  
                  <!-- 下移按钮 -->
                  <el-button
                    size="small"
                    :disabled="$index === classDetail.students.length - 1"
                    @click.stop="moveStudent($index, 'down')"
                    class="move-btn">
                    <el-icon><ArrowDown /></el-icon>
                    <span>下移</span>
                  </el-button>
                </div>
              </template>
            </el-table-column>
          </el-table>
          <el-empty v-else description="暂无学生数据" />
          
          <!-- 分页控件 -->
          <div class="pagination-container" v-if="classDetail.students.length > 0">
            <el-pagination
              :current-page="currentPage"
              :page-size="pageSize"
              :page-sizes="[10, 20, 30, 50]"
              layout="total, sizes, prev, pager, next, jumper"
              :total="classDetail.students.length"
              @update:current-page="currentPage = $event"
              @update:page-size="pageSize = $event"
            />
          </div>
        </el-tab-pane>

        <el-tab-pane label="课程管理" name="courses">
          <!-- 课程列表 -->
          <h3 class="table-title">课程列表 ({{ classDetail.courses.length }}门)</h3>
          <div class="course-grid" v-if="classDetail.courses.length > 0">
            <el-card 
              v-for="course in classDetail.courses" 
              :key="course.id" 
              class="course-card"
              shadow="hover"
              @click="showCourseDetail(course)">
              <template #header>
                <div class="course-header">
                  <span class="course-name">{{ course.couName }}</span>
                  <el-tag 
                    v-if="course.tea_id === authStore.userId" 
                    type="success"
                    size="small"
                    effect="plain">
                    我的课程
                  </el-tag>
                </div>
              </template>
              <div class="course-content">
                <p class="course-meta"><span class="label">ID:</span> {{ course.id }}</p>
                <p class="course-meta"><span class="label">创建:</span> {{ formatDate(course.createTime) }}</p>
                <p class="course-intro" v-if="course.couIntroduction">
                  {{ course.couIntroduction.substring(0, 30) }}...
                </p>
              </div>
            </el-card>
          </div>
          <el-empty v-else description="暂无课程数据" />
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 课程详情对话框 -->
    <el-dialog 
      v-model="courseDetailVisible" 
      :title="currentCourse?.couName || '课程详情'"
      width="80%"
      top="5vh"
      class="course-dialog">
      <div v-if="currentCourse">
        <div class="course-actions">
          <el-button 
            type="primary" 
            @click="editCourse"
            :disabled="!isTeachingCourse">
            修改课程信息
          </el-button>
        </div>
        
        <el-tabs v-model="activeCourseTab" class="course-detail-tabs">
          <el-tab-pane label="课程详情" name="detail">
            <div class="course-detail-content">
              <h3 class="section-title">基本信息</h3>
              <div class="detail-grid">
                <div class="detail-item">
                  <label>课程ID:</label>
                  <span>{{ currentCourse.id }}</span>
                </div>
                <div class="detail-item">
                  <label>创建时间:</label>
                  <span>{{ formatDate(currentCourse.createTime) }}</span>
                </div>
                <div class="detail-item">
                  <label>课程价格:</label>
                  <span>{{ currentCourse.cou_price }} 元</span>
                </div>
                <div class="detail-item">
                  <label>收藏数:</label>
                  <span>{{ currentCourse.cou_coll_num }}</span>
                </div>
                <div class="detail-item">
                  <label>点赞数:</label>
                  <span>{{ currentCourse.cou_like_num }}</span>
                </div>
                <div class="detail-item">
                  <label>分享数:</label>
                  <span>{{ currentCourse.cou_share_num }}</span>
                </div>
              </div>
              
              <h3 class="section-title">课程简介</h3>
              <div class="course-description">
                {{ currentCourse.couIntroduction || '暂无课程简介' }}
              </div>
            </div>
          </el-tab-pane>
          
          <el-tab-pane label="课程章节" name="chapters">
            <div class="course-chapters" v-if="currentCourse.chapters.length > 0">
              <el-table :data="currentCourse.chapters" border>
                <el-table-column prop="index" label="章节序号" width="120" />
                <el-table-column prop="title" label="章节标题" />
                <el-table-column label="操作" width="120">
                  <template #default="{row}">
                    <el-button 
                      type="text" 
                      @click="playVideo(row.videoUrl)">
                      播放视频
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <el-empty v-else description="暂无章节数据" />
          </el-tab-pane>
          
          <el-tab-pane label="课程评论" name="comments">
            <div class="course-comments" v-if="currentCourse.comments.length > 0">
              <div 
                v-for="comment in currentCourse.comments" 
                :key="comment.id"
                class="comment-item">
                <div class="comment-header">
                  <span class="student-name">学生</span>
                  <el-rate 
                    v-model="comment.score" 
                    disabled 
                    show-score
                    :max="5" />
                </div>
                <div class="comment-content">
                  {{ comment.content }}
                </div>
              </div>
            </div>
            <el-empty v-else description="暂无评论数据" />
          </el-tab-pane>
        </el-tabs>
      </div>
    </el-dialog>

    <!-- 学生进度对话框 -->
    <el-dialog
      v-model="studentProgressVisible"
      :title="`${currentStudent?.stuName || '学生'}的课程进度`"
      width="70%"
      top="5vh"
      class="progress-dialog">
      <div v-if="loadingProgress" class="progress-loading">
        <el-icon class="is-loading" color="#409EFC" :size="30">
          <Loading />
        </el-icon>
        <span>加载中...</span>
      </div>
      
      <div v-else>
        <el-table 
          :data="studentProgressData" 
          border 
          v-if="studentProgressData.length > 0"
          style="width: 100%">
          <el-table-column prop="courseName" label="课程名称" width="200" />
          <el-table-column prop="progress" label="进度" width="150">
            <template #default="{row}">
              <div class="progress-container">
                <el-progress 
                  :percentage="row.progress" 
                  :show-text="false"
                  :color="row.progress === 100 ? '#67C23A' : ''" />
                <span class="progress-text">{{ row.progress }}%</span>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="learnedDuration" label="学习时长" width="120">
            <template #default="{row}">
              {{ formatDuration(row.learnedDuration) }}
            </template>
          </el-table-column>
          <el-table-column prop="lastStudyTime" label="最后学习时间" width="180">
            <template #default="{row}">
              {{ formatDate(row.lastStudyTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="learnedStatus" label="学习状态" />
        </el-table>
        
        <el-empty v-else description="暂无学习进度数据" />
      </div>
    </el-dialog>
  </div>
</template>

<style scoped>
.class-detail-container {
  padding: 20px;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.box-card {
  border-radius: 8px;
  border: none;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.class-info {
  margin-bottom: 24px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.class-title {
  font-size: 20px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 16px;
  display: flex;
  align-items: center;
  gap: 10px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
}

.info-item {
  display: flex;
  align-items: center;
}

.label {
  color: #909399;
  margin-right: 8px;
  font-size: 14px;
}

.value {
  color: #606266;
  font-size: 14px;
}

.detail-tabs {
  margin-top: 16px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.table-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 0;
}

.sort-btn {
  border-radius: 16px;
}

/* 合并后的操作列样式 */
.student-actions {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  flex-wrap: wrap;
}

.action-btn,
.move-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 8px 12px;
}

.action-btn span,
.move-btn span {
  margin-left: 4px;
}

.el-table {
  --el-table-border-color: #ebeef5;
  --el-table-header-bg-color: #f5f7fa;
}

.el-table :deep(.el-table__cell) {
  padding: 12px 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.course-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.course-card {
  transition: all 0.3s ease;
  border-radius: 8px;
}

.course-card:hover {
  transform: translateY(-3px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.course-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.course-name {
  font-weight: 500;
  font-size: 15px;
}

.course-content {
  padding: 0 4px;
}

.course-meta {
  font-size: 13px;
  color: #606266;
  margin: 6px 0;
}

.course-meta .label {
  color: #909399;
}

.course-intro {
  font-size: 13px;
  color: #909399;
  margin-top: 8px;
  line-height: 1.5;
}

/* 对话框样式 */
.course-dialog,
.progress-dialog {
  --el-dialog-border-radius: 8px;
}

.course-actions {
  margin-bottom: 16px;
}

.course-detail-tabs {
  margin-top: 8px;
}

.section-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin: 16px 0 12px;
}

.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item label {
  font-weight: 500;
  margin-right: 8px;
  color: #606266;
  min-width: 60px;
}

.course-description {
  padding: 12px;
  background-color: #f8f9fa;
  border-radius: 4px;
  line-height: 1.6;
  color: #606266;
  font-size: 14px;
}

.comment-item {
  padding: 12px 0;
  border-bottom: 1px solid #ebeef5;
}

.comment-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 6px;
}

.student-name {
  font-size: 14px;
  color: #606266;
}

.comment-content {
  color: #909399;
  font-size: 13px;
  line-height: 1.5;
}

.progress-loading {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
}

.progress-loading span {
  margin-top: 10px;
  color: #409EFF;
}

.progress-container {
  display: flex;
  align-items: center;
  gap: 8px;
}

.progress-text {
  min-width: 40px;
  text-align: right;
  font-size: 13px;
  color: #606266;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .info-grid {
    grid-template-columns: 1fr;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .course-dialog,
  .progress-dialog {
    width: 90% !important;
  }
  
  .progress-container {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }
  
  .progress-text {
    text-align: left;
  }
  
  .student-actions {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }
  
  .action-btn,
  .move-btn {
    width: 100%;
    justify-content: flex-start;
  }
}
</style>